import 'package:flutter_todolist/util.dart';
import 'package:get/get.dart';

import '../../db/db.dart';
import '../../db/table/task_type_table.dart';

class TaskTypeController extends GetxController {
  final taskTypeList = <TaskType>[].obs;
  late TaskTypeTable taskTypeTable;

  @override
  void onInit() {
    taskTypeTable = ToDoDB().taskTypeTable;
    getTaskType();
    super.onInit();
  }

  // addTask(TaskType taskType) {
  //   taskTypeList.add(taskType);
  //   taskTypeTable.insertItem(taskType.toJson());
  // }
  //
  // updateTask(TaskType taskType) {
  //   for (int i=0; i< taskTypeList.length; i++) {
  //     if (taskTypeList[i].typeId == taskType.typeId) {
  //       taskTypeList.replaceRange(i, i+1, [taskType]);
  //     }
  //   }
  //   taskTypeTable.updateItem(taskType.typeId, taskType.toJson());
  //   // 手动更新，因为Task没有转为obs对象
  //   update();
  // }

  getTaskType() async {
    List<Map> taskMaps = await taskTypeTable.queryList();
    if (taskMaps.isNotEmpty) {
      taskTypeList.clear();
      taskTypeList.addAll(
          taskMaps.map((e) => TaskType.fromJson(e))
      );
    } else {
      // 添加默认类型
      List<TaskType> defaultTypes = [
        TaskType(
          typeId: 0,
          title: 'Personal',
          color: CustomColors.YellowIcon.value,
          icon: 'task_type/user'
        ),
        TaskType(
          typeId: 1,
          title: 'Work',
          color: CustomColors.GreenIcon.value,
          icon: 'task_type/work'
        ),
        TaskType(
          typeId: 2,
          title: 'Meeting',
          color: CustomColors.DeeppurlpleIcon.value,
          icon: 'task_type/meet'
        ),
        TaskType(
          typeId: 3,
          title: 'Shopping',
          color: CustomColors.OrangeIcon.value,
          icon: 'task_type/shop'
        ),
      ];
      taskTypeList.value = defaultTypes;
      for (var element in defaultTypes) {
        taskTypeTable.insertItem(element.toJson());
      }
    }
  }

  addTaskType(String title, int color, String icon) async {
    TaskType newType = TaskType(
        typeId: taskTypeList.length,
        title: title,
        color: color,
        icon: icon
    );
    taskTypeList.add(newType);
    taskTypeTable.insertItem(newType.toJson());
  }

  int getTaskByType(int type) {
    if (taskTypeList.isEmpty) return CustomColors.GreenIcon.value;
    for (var element in taskTypeList) {
      if (element.typeId == type) {
        return element.color ?? CustomColors.GreenIcon.value;
      }
    }
    return CustomColors.GreenIcon.value;
  }

  // deleteTask(TaskType taskType) {
  //   taskTypeList.removeWhere((element) => element.typeId == taskType.typeId);
  //   taskTypeTable.deleteItem(taskType.typeId);
  // }

  // bool hadTask(TaskType taskType) {
  //   bool exist = false;
  //   for (var element in taskTypeList) {
  //     if (element.title == taskType.title) {
  //       exist = true;
  //       return exist;
  //     }
  //   }
  //   return exist;
  // }


}